﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
using System.Windows;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Phone.Tasks;

using VideoPlay.Services;
using VideoPlay.Services.Models;
using VideoPlay.Adapters;
using Facebook.Client;
using System.Windows.Threading;

namespace VideoPlay.PhoneClient.ViewModels
{
    public class VideoViewModel : ViewModel
    {
        public VideoViewModel(
            INavigationService navigationService,
            IPhoneService phoneService,
            IndicatorViewModel indicator)
            : base(navigationService, phoneService, indicator, new Uri(@"/Views/VideoListView.xaml", UriKind.Relative))
        {
            ShareCommand = new DelegateCommand(this.ShareOnFB);
        }

        private int id;
        public int ID
        {
            get { return this.id; }
            set
            {
                this.id = value;
                this.RaisePropertyChanged(() => this.ID);
            }
        }

        private string youtubeId;
        public string YoutubeId
        {
            get { return this.youtubeId; }
            set
            {
                this.youtubeId = value;
                this.RaisePropertyChanged(() => this.YoutubeId);
            }
        }

        private string videoUrl;
        public string VideoUrl
        {
            get
            {
                return this.videoUrl;
            }
            set
            {
                this.videoUrl = value;
                this.RaisePropertyChanged(() => this.VideoUrl);
            }
        }

        private BitmapImage videoImage;
        public BitmapImage VideoImage
        {
            get
            {
                if (this.videoImage == null)
                    this.videoImage = new BitmapImage();
                return this.videoImage;
            }
            set
            {
                this.videoImage = value;
                this.RaisePropertyChanged(() => this.VideoImage);
            }
        }

        private string imageUrl = string.Empty;
        public string ImageUrl
        {
            get { return this.imageUrl; }
            set
            {
                this.imageUrl = value;
                this.RaisePropertyChanged(() => this.ImageUrl);
            }
        }

        private string videoName = string.Empty;
        public string VideoName
        {
            get { return this.videoName; }
            set
            {
                this.videoName = value;
                this.RaisePropertyChanged(() => this.VideoName);
            }
        }

        private string duration = string.Empty;
        public string Duration
        {
            get { return this.duration; }
            set
            {
                this.duration = value;
                this.RaisePropertyChanged(() => this.Duration);
            }
        }

        private bool like = false;
        public bool Like
        {
            get { return this.like; }
            set
            {
                this.like = value;
                this.RaisePropertyChanged(() => this.Like);
            }
        }

        public DelegateCommand ShareCommand { get; set; }

        private async void ShareOnFB()
        {
            //this.NavigationService.Navigate(new Uri("/Views/VideoShareFBView.xaml", UriKind.Relative));

            if (!App.isAuthenticated)
            {
                App.isAuthenticated = true;
                await Authenticate();
            }
        }

        private FacebookSession session;
        private async Task Authenticate()
        {
            string message = String.Empty;
            try
            {
                session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream,publish_actions");
                App.AccessToken = session.AccessToken;
                App.FacebookId = session.FacebookId;

                ShareVideo();
            }
            catch (InvalidOperationException e)
            {
                message = "Login failed! Exception details: " + e.Message;
                MessageBox.Show(message);
            }
        }

        private async void ShareVideo()
        {
            this.Indicator.Show();
            
            Facebook.FacebookClient fbClient = new Facebook.FacebookClient(App.AccessToken);
            await fbClient.PostTaskAsync(String.Format("/me/{0}:share", "video-app-client"), 
                                        new {
                                            video = VideoUrl, 
                                            message = "The {0} video was shared from Video Play application",
                                            other = VideoUrl
                                        });
            
            this.Indicator.Hide();
            MessageBox.Show(string.Format("The {0} video has been shared.",VideoName));
        }

        private string GetFilenameFromUrl(string url)
        {
            Uri uri = new Uri(url);
            if (uri.IsAbsoluteUri)
            {
                return System.IO.Path.GetFileName(uri.LocalPath);
            }

            return string.Empty;
        }

        public void LikeUnlike()
        {
            this.Like = !like;
            if (this.Like)
                FavoriteFacade.Save(new List() 
                { 
                    lcLocalId = this.ID, 
                    lcYoutubeId = this.YoutubeId, 
                    image = this.ImageUrl, 
                    url = this.VideoUrl,
                    duration = ConvertStringToTimespan(this.Duration),
                    title = this.VideoName
                });
            else
                FavoriteFacade.Remove(new List()
                {
                    lcLocalId = this.ID,
                    lcYoutubeId = this.YoutubeId
                });
        }

        private TimeSpan ConvertStringToTimespan(string time)
        {
            string[] array = time.Split(new char[]{':'});
            int hour = Convert.ToInt32(array[0]);
            int minute = Convert.ToInt32(array[1]);
            int second = Convert.ToInt32(array[2]);

            return new TimeSpan(hour,minute,second);
        }

        public void Play()
        {
            try
            {
                ((App)Application.Current).ViewModelLocator.PlayVideoViewModel.VideoUrl = this.VideoUrl;
                this.NavigationService.Navigate(new Uri("/Views/PlayVideoView.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ops!!! Cannot play the video. Details: " + ex.Message);
            }
        }

        public override void OnPageResumeFromTombstoning()
        {

        }
    }
}
